package com.yj.web.service.impl;

import com.yj.web.dao.mapper.AdminUserMapper;
import com.yj.web.dao.mapper.MessageMapper;
import com.yj.web.dao.po.admin.Message;
import com.yj.web.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * Created by yanlinyang on 2017/7/4.
 */
@Service("messageService")
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private AdminUserMapper adminUserMapper;

    @Override
    public List<Message> listMessageByReceiver(String phone, int page, int size) {
        int offset = (page - 1) * size;
        List<Message> msgs = messageMapper.listMessageByReceiver(phone, offset, size);
        return msgs;
    }

    @Override
    public int countMessageByReceiver(String phone) {
        int num = messageMapper.countMessageByReceiver(phone);
        return num;
    }

    @Override
    public List<Message> listAllMessage(int page, int size) {
        int offset = (page - 1) * size;
        List<Message> msgs = messageMapper.listMessage(offset, size);
        return msgs;
    }

    @Override
    public int countMessage() {
        int num = messageMapper.countMessage();
        return num;
    }

    @Override
    public long insertMessage(Message message) {
        if (message.getReceiverStr().equals("all")) {
            Set<String> phones = adminUserMapper.listAllUserPhone();
            String[] phonesArr = phones.toArray(new String[]{});
            String phonesStr = phonesArr.toString();
            message.setReceiverStr(phonesStr);
            message.setReceivers(phones);
            message.setNumber(phones.size());
        } else {
            String phones = message.getReceiverStr();
            String[] phonesArr = phones.split(",");
            message.setNumber(phonesArr.length);
        }
        // TODO: 2017/8/2  sendMsg

        return messageMapper.insertMessage(message);
    }

    @Override
    public boolean updateMessage(long id) {
        boolean flag = messageMapper.updateMessage(id);
        return flag;
    }
}
